#include "../include/Buffer.hpp"
#include <iostream>
#include <fstream>
#include <vector>
#include <string>

//字符串分割函数---将src字符串按照分割字符串sep进行分割，得到的各个字符串放到array中，最终返回子串的数量
size_t  Split(const std::string& src, const std::string& sep, std::vector<std::string>* array)
{
    int offset = 0;
    while(offset < src.size())
    {
        //在src字符串中偏移量offset处，开始向后查找sep字符/子串，返回查找到的位置
        size_t pos = src.find(sep, offset);
        if(pos == std::string::npos)
        {
            //走到这里表示没有找到特定的字符---说明整个src字符串就是一整个子串
            array->push_back(src.substr(offset));
            return array->size();
        }
        //当前字符串是一个空的，没有内容
        if(pos == offset)
        {
            offset = pos + 1;
            continue;
        }
        //走到这里说明找到了sep字符，截取字符就可以了
        array->push_back(src.substr(offset, pos - offset));
        //更新寻找sep字符的起始位置
        offset = pos + 1;
    }

    return array->size();
}

//读取文件的所有内容，将读取的内容放到Buffer对象中
static bool ReadFile(const std::string& filename, Muduo::Buffer* buf)
{
    //以二进制的方式读取文件
    std::ifstream ifs(filename, std::ios::binary);
    if(ifs.is_open() == false)
    {
        LOGERROR("open %s file failed!", filename.c_str());
        return false;
    }
    //获取文件的大小
    size_t fsize = 0;
    ifs.seekg(0, ifs.end);
    fsize = ifs.tellg();
    ifs.seekg(0, ifs.beg);//移动到文件的起始位置，准备读取文件；
    //读取文件
    //保证buf有足够的空间写入
    buf->EnsureWriteSpace(fsize);
    ifs.read(buf->WritePosition(), fsize);
    if(ifs.good() == false)//判断读取文件是否成功
    {
        LOGERROR("read %s file failed!", filename.c_str());
        ifs.close();
        return false;
    }
    //移动buf的写位置偏移
    buf->MoveWriteOffest(fsize);
    ifs.close();
    return true;
}
//向文件写入数据
static bool WriteFile(const std::string& filename, Muduo::Buffer& buf)
{
    //trunc是将文件的大小截断为0，即就是覆盖文件中原有的内容，从文件的起始位置写入；
    std::ofstream ofs(filename, std::ios::binary | std::ios::trunc);
    if(ofs.is_open() == false)
    {
        LOGERROR("open %s file failed!", filename.c_str());
        return false;
    }
    //写入数据
    ofs.write(buf.ReadPosition(), buf.ReadAbleSize());
    if(ofs.good() == false)
    {
        LOGERROR("write %s file failed!", filename.c_str());
        ofs.close();
        return false;
    }
    buf.MoveReadOffest(buf.ReadAbleSize());
    ofs.close();
    return true;
}
//URL编码，避免URL中资源路径与查询字符串中的特殊字符与HTTP请求中的特殊字符产生歧义
//编码格式：将特殊字符的ASCII值，转换为两个16进制字符，前缀%； 比如 C++ ---> C%2B%2B
//不编码的特殊字符：RFC3986文档规定字符 . - _ ~ 和 字母、数字属于绝对不编码字符
//RFC3986文档规定，特殊字符编码格式：%HH
//W3C标准中规定，查询字符串中的空格，需要编码为 + ， 解码则是 + 转为空格
static std::string UrlEncode(const std::string url, bool convertSpaceTOPlus)
{
    std::string ret;
    for(auto& c : url)
    {
        //如果是字符. - _ ~ 和 字母、数字不需要编码
        if(c == '.' || c == '-' || c == '_' || c == '~' || isalnum(c))
        {
            ret += c;
        }
        else if(c == ' ' && convertSpaceTOPlus)
        {
            ret += '+';
        }
        else
        {
            char tmp[4] = {0};
            snprintf(tmp, sizeof(tmp), "%%%02X", c);
            ret += tmp;
        }
    }
    return ret;
}
static char HEXTOI(char c)
{
    char res;
    if(c >= '0' && c <= '9')
    {
        res = c - '0';
    }
    else if (c >= 'a' && c <= 'z')
    {
        res = c - 'a' + 10;
    }
    else if(c >= 'A' && c <= 'Z')
    {
        res = c - 'A' + 10;
    }
    return res;
}
//URL解码
static std::string UrlDecode(const std::string url, bool convertPlusTOSpace)
{
    //遇到%字符，则将紧随其后的2个字符，转换为数字，第一个数字左移4位置(乘以16)，然后加上第二个数字；
    std::string ret;
    for(int i = 0; i < url.size(); ++i)
    {
        if(url[i] == '+' && convertPlusTOSpace)
        {
            ret += ' ';
        }
        else if(url[i] == '%')
        {
            char a = HEXTOI(url[i+1]);
            char b = HEXTOI(url[i+2]);
            char c = a * 16 + b;
            ret += c;
            i += 2;
        }
        else 
        {
            ret += url[i];
        }
    }
    return ret;
}
//响应状态码的描述信息获取
static std::string StatuDesc(int statCode)
{
    std::unordered_map<int, std::string> statMsg={
        {100,  "Continue"},
        {101,  "Switching Protocol"},
        {102,  "Processing"},
        {103,  "Early Hints"},
        {200,  "OK"},
        {201,  "Created"},
        {202,  "Accepted"},
        {203,  "Non-Authoritative Information"},
        {204,  "No Content"},
        {205,  "Reset Content"},
        {206,  "Partial Content"},
        {207,  "Multi-Status"},
        {208,  "Already Reported"},
        {226,  "IM Used"},
        {300,  "Multiple Choice"},
        {301,  "Moved Permanently"},
        {302,  "Found"},
        {303,  "See Other"},
        {304,  "Not Modified"},
        {305,  "Use Proxy"},
        {306,  "unused"},
        {307,  "Temporary Redirect"},
        {308,  "Permanent Redirect"},
        {400,  "Bad Request"},
        {401,  "Unauthorized"},
        {402,  "Payment Required"},
        {403,  "Forbidden"},
        {404,  "Not Found"},
        {405,  "Method Not Allowed"},
        {406,  "Not Acceptable"},
        {407,  "Proxy Authentication Required"},
        {408,  "Request Timeout"},
        {409,  "Conflict"},
        {410,  "Gone"},
        {411,  "Length Required"},
        {412,  "Precondition Failed"},
        {413,  "Payload Too Large"},
        {414,  "URI Too Long"},
        {415,  "Unsupported Media Type"},
        {416,  "Range Not Satisfiable"},
        {417,  "Expectation Failed"},
        {418,  "I'm a teapot"},
        {421,  "Misdirected Request"},
        {422,  "Unprocessable Entity"},
        {423,  "Locked"},
        {424,  "Failed Dependency"},
        {425,  "Too Early"},
        {426,  "Upgrade Required"},
        {428,  "Precondition Required"},
        {429,  "Too Many Requests"},
        {431,  "Request Header Fields Too Large"},
        {451,  "Unavailable For Legal Reasons"},
        {501,  "Not Implemented"},
        {502,  "Bad Gateway"},
        {503,  "Service Unavailable"},
        {504,  "Gateway Timeout"},
        {505,  "HTTP Version Not Supported"},
        {506,  "Variant Also Negotiates"},
        {507,  "Insufficient Storage"},
        {508,  "Loop Detected"},
        {510,  "Not Extended"},
        {511,  "Network Authentication Required"}
    };
    auto it = statMsg.find(statCode);
    if(it != statMsg.end())
    {
        return it->second;
    }
    return "UnKnow";
}

//根据文件后缀名获取文件mime
static std::string ExMime(const std::string& filename)
{
    std::unordered_map<std::string, std::string> mimeMsg = {
        {".aac",        "audio/aac"},
        {".abw",        "application/x-abiword"},
        {".arc",        "application/x-freearc"},
        {".avi",        "video/x-msvideo"},
        {".azw",        "application/vnd.amazon.ebook"},
        {".bin",        "application/octet-stream"},
        {".bmp",        "image/bmp"},
        {".bz",         "application/x-bzip"},
        {".bz2",        "application/x-bzip2"},
        {".csh",        "application/x-csh"},
        {".css",        "text/css"},
        {".csv",        "text/csv"},
        {".doc",        "application/msword"},
        {".docx",       "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
        {".eot",        "application/vnd.ms-fontobject"},
        {".epub",       "application/epub+zip"},
        {".gif",        "image/gif"},
        {".htm",        "text/html"},
        {".html",       "text/html"},
        {".ico",        "image/vnd.microsoft.icon"},
        {".ics",        "text/calendar"},
        {".jar",        "application/java-archive"},
        {".jpeg",       "image/jpeg"},
        {".jpg",        "image/jpeg"},
        {".js",         "text/javascript"},
        {".json",       "application/json"},
        {".jsonld",     "application/ld+json"},
        {".mid",        "audio/midi"},
        {".midi",       "audio/x-midi"},
        {".mjs",        "text/javascript"},
        {".mp3",        "audio/mpeg"},
        {".mpeg",       "video/mpeg"},
        {".mpkg",       "application/vnd.apple.installer+xml"},
        {".odp",        "application/vnd.oasis.opendocument.presentation"},
        {".ods",        "application/vnd.oasis.opendocument.spreadsheet"},
        {".odt",        "application/vnd.oasis.opendocument.text"},
        {".oga",        "audio/ogg"},
        {".ogv",        "video/ogg"},
        {".ogx",        "application/ogg"},
        {".otf",        "font/otf"},
        {".png",        "image/png"},
        {".pdf",        "application/pdf"},
        {".ppt",        "application/vnd.ms-powerpoint"},
        {".pptx",       "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
        {".rar",        "application/x-rar-compressed"},
        {".rtf",        "application/rtf"},
        {".sh",         "application/x-sh"},
        {".svg",        "image/svg+xml"},
        {".swf",        "application/x-shockwave-flash"},
        {".tar",        "application/x-tar"},
        {".tif",        "image/tiff"},
        {".tiff",       "image/tiff"},
        {".ttf",        "font/ttf"},
        {".txt",        "text/plain"},
        {".vsd",        "application/vnd.visio"},
        {".wav",        "audio/wav"},
        {".weba",       "audio/webm"},
        {".webm",       "video/webm"},
        {".webp",       "image/webp"},
        {".woff",       "font/woff"},
        {".woff2",      "font/woff2"},
        {".xhtml",      "application/xhtml+xml"},
        {".xls",        "application/vnd.ms-excel"},
        {".xlsx",       "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
        {".xml",        "application/xml"},
        {".xul",        "application/vnd.mozilla.xul+xml"},
        {".zip",        "application/zip"},
        {".3gp",        "video/3gpp"},
        {".3g2",        "video/3gpp2"},
        {".7z",         "application/x-7z-compressed"}
    };
    //获取文件后缀
    size_t pos = filename.find_last_of('.');
    if(pos == std::string::npos)
    {
        //没有找到文件后缀，就表示当前文件是一个二进制流
        return "application/octet-stream";
    }
    std::string extension = filename.substr(pos);
    //根据扩展名获取mime
    auto it = mimeMsg.find(extension);
    if(it != mimeMsg.end())
    {
        return it->second;
    }
    return "application/octet-stream";
}
//判断一个文件是一个目录
static bool IsDirectory(const std::string& filename)
{
    //获取文件的属性，stat接口是用来获取文件状态的
    struct stat st;
    int ret = stat(filename.c_str(), &st);
    if(ret < 0)
    {
        return false;
    }
    //宏S_ISDIR是通过文件的属性来判断，是否是一个目录
    return S_ISDIR(st.st_mode);
}
//判断一个文件是一个普通文件
static bool IsRegular(const std::string& filename)
{
    //获取文件的属性
    struct stat st;
    int ret = stat(filename.c_str(), &st);
    if(ret < 0)
    {
        return false;
    }
    //宏S_ISDIR是通过文件的属性来判断，是否是一个普通文件
    return S_ISREG(st.st_mode);
}

static bool ValidPath(const std::string& path)
{
    /*判断HTTP请求的资源路径有效性的思想：按照 / 进行路径的分割，根据有多少个子目录，计算目录的深度，有多少层，深度不能小于0；
    当遇到 .. 目录的深度就 -- */
    int level = 0;
    std::vector<std::string> subDir;
    Split(path, "/", &subDir);
    for(auto& dir : subDir)
    {
        if(dir == "..")
        {
            level--;
            //任意一层走出web根目录就任务资源路径有问题
            if(level < 0)
            {
                return false;
            }
        }
        else
        {
            level++;
        }
    }
    return true;
}
int main ()
{
    // std::string src = "abcdef";
    // std::vector<std::string> array;
    // Split(src, ",", &array);
    // for(auto& s : array)
    // {
    //     std::cout << s << std::endl;
    // }

    // Muduo::Buffer buf;
    // bool ret = ReadFile("../src/server.cc", &buf);
    // if(ret == false)
    // {
    //     LOGDEBUG("read file fialed!");
    //     return -1;
    // }
    // ret = WriteFile("../src/test", buf);
    // if(ret == false)
    // {
    //     LOGDEBUG("write file fialed!");
    //     return -1;
    // }

    // std::string str1 = UrlEncode("C  ", true);
    // std::cout << str1 << std::endl;
    // std::string str2 = UrlDecode(str1, true);
    // std::cout << str2 << std::endl;

    // std::cout << ExMime("a.json") << std::endl;
    // std::cout << ExMime("a.xhtml") << std::endl;
    // std::cout << ExMime("a.xxxx") << std::endl;

    // std::cout << IsDirectory("../src") << std::endl;
    // std::cout << IsRegular("../src/server.cc") << std::endl;

    std::cout << ValidPath("/src/server.cc") << std::endl;
    std::cout << ValidPath("/src/../server.cc") << std::endl;
    std::cout << ValidPath("/src/../../server.cc") << std::endl;

    return 0;
}

